import {createAsyncThunk, createEntityAdapter, createSlice} from "@reduxjs/toolkit";
import {client} from "../../api/client";

export const fetchUsers = createAsyncThunk('users/fetchUsers', async () => {
  const res = await client.get('/fakeApi/users')
  return res.data
})

// export const selectAllUsers = state => state.users
//
// export const selectUserById = (state, userId) => {
//   return state.users.find(user => user.id === userId)
// }

const usersAdapter = createEntityAdapter()

const initialState = usersAdapter.getInitialState()

const usersSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {},
  // extraReducers (builder) {
  //   builder.addCase(fetchUsers.fulfilled, (state, action) => {
  //     return action.payload
  //   })
  // }
  extraReducers: {
    [fetchUsers.fulfilled]: usersAdapter.setAll
  }
})

export default usersSlice.reducer
export const {
  selectAll: selectAllUsers,
  selectById: selectUserById
} = usersAdapter.getSelectors(state => state.users)
